package com.vdongchina.thread.base;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 第四课, 线程间通信
 * <p>
 * volatile 保证了线程变量的可见性,用于申明共享变量
 * synchronized 保证了线程的排他性
 * <p>
 * javap -v classes/com/vdongchina/thread/base/ThreadCommunicationDemo.class 查看
 * <p>
 * <p>
 * wait() notify()/notifyAll() 对统一对象操作,实现不同线程中对
 */
public class ThreadCommunicationDemo {

    public static void main(String[] args) {

        //对ThreadCommunicationDemo加锁
        synchronized (ThreadCommunicationDemo.class) {
        }
        m();

        waitNotify();
    }

    //flags: ACC_PUBLIC, ACC_STATIC, ACC_SYNCHRONIZED  排他性
    public static synchronized void m() {

    }


    static volatile boolean flag = true;
    static Object lock = new Object();  //申明一个静态当一个锁的对象


    /***
     * 一个线程去唤醒另外一个线程
     *  wait() 被notify()后并不会立即到running 而是在 block 状态, 等待cpu分配资源执行 ,如果涉及到线程间通信一定要加锁
     *
     *  synchronzied(对象){
     *        while(条件不满足){
     *            对象.wait()
     *        }
     *        对应逻辑处理
     *   }
     *
     */
    public static void waitNotify() {

        Thread waitThread = new Thread(new Wait(), "WaitThread");
        waitThread.start();
        SleepUtils.second(5);
        Thread notifyThread = new Thread(new Notify(), "NotifyThread");
        notifyThread.start();

    }


    static class Wait implements Runnable {
        @Override
        public void run() {
            synchronized (lock) {
                while (flag) {
                    try {
                        System.out.println(Thread.currentThread() + " flag is true.  @ " + new SimpleDateFormat("HH:mm:ss").format(new Date()));
                        lock.wait();  //整个线程进入wait状态,循环停止,wait会释放锁
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(Thread.currentThread() + " flag is false. running @" + new SimpleDateFormat("HH:mm:ss").format(new Date()));
            }
        }
    }

    static class Notify implements Runnable {

        @Override
        public void run() {
            synchronized (lock) {
                System.out.println(Thread.currentThread() + " flag is true " + new SimpleDateFormat("HH:mm:ss").format(new Date()));
                lock.notifyAll(); //通知不会释放锁,线程进入到block状态
                flag = false;
                SleepUtils.second(5);
            }

            synchronized (lock) {
                System.out.println(Thread.currentThread() + " hold lock again. sleep @ " + new SimpleDateFormat("HH:mm:ss").format(new Date()));
                SleepUtils.second(5);
            }

        }
    }

    static class SleepUtils {
        public static void second(int i) {
            try {
                TimeUnit.SECONDS.sleep(i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }


}
